package com.example.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;

import org.springframework.stereotype.Component;

@Component
public class PayUtil {
    //个人appid，
    private final String APP_ID = "9021000149699011";
    //编码格式
    private final String CHARSET = "UTF-8";
    //秘钥生成工具生成的 应用私钥
    private final String APP_PRIVATE_KEY ="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCyZYft3AHdJCYWqJQtietYNNNcfJMTQm9JP0UUoZaZr3aywOLNlzKg31Gq+IpurzQHkrXoPlrAmk1r3+wrc1CXDweY8S4IdFoyYxT71ImniLtPcPdavG9X5CGfdq5wzDaYnGN+sHIMpwX951AmQNwNWUaqPNNH6IoRR+NBQkpYdpPU9yGibzRxZFOFCPxvCK/MiYG6A+Ru5MgnJZ1S5hoF1XYUK26ZFWQgiYOOOxxmJsRWYA9n0mCJwImV+Irwme/PqPl/EhtWrc+jkZW71tG9oGkhp++mjKSC82O3A9+3rWQJkSFjQXfs0ZtfrwVMmZwbpP7CRJsr13TSHOB/Ww/rAgMBAAECggEAaIDPksf5k4jUgxt3ygFsCvzO//O92F9nf5n/pqlN5nOB7g7ODa9PqiuH1MbJmTMrIHCR/R1h3kfFqLbAy2c+w267fZ1y4OL/31ppdWg4xxpy14OOcunFs8/g3mAQqeUG6nlaU2GbPcwt12HEctQ10+ADZEBDaHFRR/Q7rQPfN1grP1ACEC3QiEf7YcyH7C+SKlTXc4LCOwwXZL4+qpjbOHCTsdpgh64ejMRQE4PCpsMdr90c87Ebonx5uHEuxyKDOXMuc0j7/t5tSkC7agY0K8iSJiB7T+EMW8wiM3EV445kxTKsEF26vYwoP/RRPGdItDo2QqX1xTzDxjbH1/ATuQKBgQDuRUnsWrkob0FyIEqbwThs+mH5haJjIHiUrrsOrqt87khmQbMHgGI6ieXyo+lg99/WG0MEHV/RTC+JaMjL9Ch9qeNBo6Qa37WCWztbyk1fC49cnbHBnSIkIMiBmAP6Lj3W6UKtUTM0CV5/jgdaRSNHJmlXPZGnZREqyuVdKxdbDQKBgQC/q7pm7ID/E/hn9ASQCC2WU+sKEOeNNCk48H5TZTXwv+e430r4Ml/31LN4iZPi9OB4YihC5E2b036Aa6KXa9++ICes1o8Z3XATWC4t3nR5oyUS88wG6yWCqj9vTb3yFQo3+3fcghHs4uB5xFP7BDRlTGF0DBbcCvyrI0QyEm341wKBgCDoCtSMlwPBkb1MPmGSZtOOJNfMH+gmxOBr3UOi1eY0FmWg7zO7BFXnU42WG5YbxZsROsknsWL7bZlBknGwb6MjQlJ/YhugB7ZQGTuNDfBxbUQyNylxJRTuPiK/ttTna/zxTBcZnsOyA44ENHnAEKYz5Np6k1IWAC/zw4eBewFFAoGASiCeTKP3F6+fiISlJxcimlsGMbRr+P5NWwoXsSUZgWyWr7ccBXVmDDEk399FZKcUETrVG1m0cimPaRc3oJxFwgApl/y7B2POroyR/4djQI/KDNRg+eQDc89oDSHh7jgY5aHJr2xWhmkQK8e0OwZbRToPDpSGWr+dDIrtGvhps60CgYEAhhoRPGLixJHKyYCp9JLX65QuKV3Vgugp8HZaFAHqapZPTuqMUSvDxxcUC4SigbW2tiKcuAtAu++UeCy1SK0JDJZXGwJJVAiylHrK0+rXYlO38tZwuj04h0hIzp+NHG53anggRG79vC1Y9kvGjHxtYd84ishb92cFYL4FGOLom9w=" ;
    // 支付宝公钥，这是在沙箱应用-接口加签方式-自定义秘钥-  添加应用公钥以后生成的支付宝公钥
    private final String ALIPAY_PUBLIC_KEY ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjRPdt75Z6hDqEurkFDuvU/QIqIUpsBk10Dh1mXydsGKNdPrW/OrWx6AeEPK5xyxcBlRXz18wi9xYsSrjlmICewaJCU1Hyqitg2uYbtXAbrlibOQX6iXvx90b0pWHbppkHSed++7rPLfrJrvHgP/pRTMUxaQBkTpH4Lbrzpg9zbasZaecxOqLz3hLVwhWUbICP+e2MtrheiwPLOrT4Z49/vLK5VnIWipm24tqvseFPygxy4P+K1w0QVsUi9fPMMeDk9Sg25XbdVBoan+4dqjbAIHX/+T1LMUaY0psP561Vl9OScE/bAZpTA0p3m2KogEKKDhf+BZZRdSyuJJT4wymTQIDAQAB";
    // 支付宝网关地址，沙箱应用页面可直接查看
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    // 请求格式
    private final String FORMAT = "JSON";
    // 加密算法
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会先异步调用本方法,必须为公网地址,优先在这里做业务逻辑处理
    //但是由于这里需要外网，我们在本地测试可以使用内网穿透的方式模拟公网ip请求
    private final String NOTIFY_URL = "http://w936362c.natappfree.cc/api/alipay/notify";
    //支付宝同步通知路径,也就是当付款完毕后，可以自定义跳转本项目的自定义页面,可以不是公网地址,可以调到我的订单页面
    private final String RETURN_URL = "http://localhost:8080/api/alipay/return";

    private AlipayClient alipayClient = null;
    /**
     * 向支付宝发送支付请求
     *
     * @param outTradeNo  商户订单号
     * @param totalAmount 订单总金额
     * @param subject     订单标题
     */
    public String sendRequestToAlipay(String outTradeNo, Double totalAmount, String subject) throws AlipayApiException {
        // 初始化AlipayClient，配置支付宝网关、应用ID、私钥等参数
        alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        // 创建支付宝支付请求对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 设置异步回调地址（支付宝服务器异步通知商户服务器的地址）
        alipayRequest.setNotifyUrl(NOTIFY_URL);
        // 设置同步回调地址（用户付款后跳转的页面）
        alipayRequest.setReturnUrl(RETURN_URL);
        //商品描述（可空）
        String body = "";
        // 构建业务参数JSON对象
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("total_amount", totalAmount);
        bizContent.put("subject", subject);
        bizContent.put("body", body);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(bizContent.toJSONString()); // 注意使用toJSONString()
        // 执行支付请求并获取返回结果
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("返回的结果："+result );
        return result;
    }

    /**
     * 查询指定订单的信息
     *
     * @param id 订单编号
     * @return 支付查询结果的原始响应体
     */
    public String query(String id){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        // 构建业务参数JSON对象
        JSONObject bizContent = new JSONObject();
        // 商户订单号
        bizContent.put("out_trade_no", id);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        String body=null;
        try {
            // 执行查询请求并获取响应
            response = alipayClient.execute(request);
            body = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return body;
    }
}
